package com.hl.toolkit.pay.controller;

import com.alipay.demo.trade.ALIPayScan;
import com.tycoin.account.slaveentity.TycoinAccountRecharge;
import com.tycoin.account.slaveservice.TycoinAccountRechargeCallbackProcessService;
import com.tycoin.account.slaveservice.TycoinAccountRechargeService;
import com.tycoin.common.entity.AliWxPayInfo;
import com.tycoin.user.slaveentity.TycoinUser;
import com.tycoin.user.slaveservice.TycoinUserService;
import com.util.*;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


/**
 * 支付宝支付
 */
@Controller
 @RequestMapping(value={"/interface/alipayScann"})
public class AlipayPayScannController extends AbstractController{

	private static final Logger logger = LoggerFactory.getLogger(AlipayPayScannController.class);
    
	@Autowired
	private TycoinAccountRechargeService tycoinAccountRechargeService;
	@Autowired
	private TycoinAccountRechargeCallbackProcessService tycoinAccountRechargeCallbackProcessService; 
	
	
	@Autowired
	private TycoinUserService tycoinUserService; 
	
	/**
	 * 
	 */
	@RequestMapping(value = "/ALipaySc",produces="application/json;charset=UTF-8",method=RequestMethod.GET)
	@ResponseBody  
 	public String aliScannPay( 
  			HttpServletRequest request,
			HttpServletResponse reponse) {
 	     	String result="";
 	     	
                 Map<String,String> putMap=new HashMap<String,String>();
                
             putMap.put("AuthCode", request.getParameter("AuthCode"));
             putMap.put("Charge", request.getParameter("Charge"));
             putMap.put("GoodsName", request.getParameter("GoodsName"));
              putMap.put("UserId", request.getParameter("UserId"));
             putMap.put("AddIp", IpRequestUtils.getRemoteHost(request));
   	     	result=isNotparam(putMap);
  		     if(StringUtils.isNotBlank(result)){
  		    	 return result;
 		     }

              AliWxPayInfo payInfo=new AliWxPayInfo();
 			payInfo.setAuthCode(putMap.get("AuthCode"));
			payInfo.setCharge(Double.valueOf(putMap.get("Charge")));
			payInfo.setGoodsName(putMap.get("GoodsName"));
 			payInfo.setUserId(Integer.valueOf(putMap.get("UserId")));
			payInfo.setAddIp(putMap.get("AddIp"));
			payInfo.setCharge(Integer.valueOf(putMap.get("Charge")));
 
		
		TycoinAccountRecharge tycoinAccountRecharge=new TycoinAccountRecharge();
		
  		if (null != payInfo)   {
			if (payInfo.getCharge() > 0) {
				long dateTime=System.currentTimeMillis();
 				  String outTradeNo = "ALTran" + dateTime
                  + (long) (Math.random() * 1000000000L);
  				tycoinAccountRecharge.setPaymentId(outTradeNo);
   	  				tycoinAccountRecharge.setLogno( RandomUtils.getRandomString(16));
   				 tycoinAccountRecharge.setFee("0");
 				 tycoinAccountRecharge.setIsOnline("0");
 				 tycoinAccountRecharge.setMoney(String.valueOf((int)payInfo.getCharge()));
    				tycoinAccountRecharge.setMoneyfloat((float)payInfo.getCharge()/100);
  				  SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
 				 String nowDate = format.format(dateTime);  
 			    tycoinAccountRecharge.setDateTime(dateTime);
 			   tycoinAccountRecharge.setPaymentTime(nowDate);
 			     tycoinAccountRecharge.setType(String.valueOf(payInfo.getPayType()));
 			     tycoinAccountRecharge.setUserId(String.valueOf(payInfo.getUserId()));
 			     tycoinAccountRecharge.setAddip(payInfo.getAddIp());
 			    tycoinAccountRecharge.setPayMode(2);
 			    tycoinAccountRecharge.setPaymentStatus(0);
   			     
  			   tycoinAccountRechargeService.save(tycoinAccountRecharge);
   			 double orderAmount = payInfo.getCharge();
 				  String orderName =  "煌亦全支付";
  			    	ALIPayScan aLIPayScann = new ALIPayScan();
   				   NumberFormat ddf1=NumberFormat.getNumberInstance() ;
   				 ddf1.setMaximumFractionDigits(2); 
    				   result= aLIPayScann.testTradePay(outTradeNo,
   						   "煌亦全支付"+orderAmount,
  						   String.valueOf(ddf1.format(payInfo.getCharge()/100)),Integer.valueOf(tycoinAccountRecharge.getMoney()),payInfo.getAuthCode(),"0.0",
  						   "",   orderName,"test_operator_id");
 			        JSONObject alipay_trade_pay_response = JSONObject.fromObject(result);
 			        JSONObject array = JSONObject.fromObject(alipay_trade_pay_response.get("alipay_trade_pay_response"));
 					String code= array.getString("code");
					  String msg= array.getString("msg");
					  String trade_no=array.getString("trade_no");
					  tycoinAccountRecharge.setReturnText(result);
					  tycoinAccountRecharge.setShopTradeNo(trade_no);
 			 		  if("10000".equals(code)&&"Success".equals(msg)){
  			 			  
 			 			  tycoinAccountRecharge.setPaymentStatus(1);
 			 			tycoinAccountRechargeService.save(tycoinAccountRecharge);
  			         	tycoinAccountRechargeCallbackProcessService.rechargeCallbackProcess(tycoinAccountRecharge); 
 		             }else{
 		            	tycoinAccountRecharge.setPaymentStatus(2);
  			 			tycoinAccountRechargeService.save(tycoinAccountRecharge);
  		             }
 		                   result="{\"result_code\":\""+code+"\",\"return_msg\":\""+msg+"\",\"cash_fee\":\""+String.valueOf(payInfo.getCharge())+"\",\"transaction_id\":\""+outTradeNo+"\"}";
 		                   System.out.println("打印result的结果："+result);
			} else {

			}
		} 
 		return result;
 	}
	
	
	@RequestMapping(value = "/RollbackcannPayByTran",produces="application/json;charset=UTF-8",method=RequestMethod.GET)
	@ResponseBody
	public String backcannPayByTran(HttpServletRequest request, HttpServletResponse response) {
 		String result = "";

		String transactionID = request.getParameter("transactionID");
		if(StringUtils.isBlank(transactionID)){
            result="{\"result_code\":\"2001\",\"return_msg\":\" transactionID参数不能为空\"}";
            return result;
		}
   		TycoinAccountRecharge tycoinAccountRecharge= tycoinAccountRechargeService.findOneBypaymentId(transactionID);
 		if(tycoinAccountRecharge==null){
               result="{\"result_code\":\"6001\",\"return_msg\":\"未找到该订单号\"}";
     		return result;
  		}
		try {
			ALIPayScan aLIPayScann = new ALIPayScan();
			result = aLIPayScann.test_trade_refund(transactionID,String.valueOf(tycoinAccountRecharge.getMoneyfloat()));
			tycoinAccountRecharge.setReturnText(result);
			//{\"result_code\":\"10000\",\"return_msg\":\"OK\",transaction_id:\""+outTradeNo+"\"}
		    JSONObject alipay_trade_pay_response = JSONObject.fromObject(result);
		    if("10000".equals(alipay_trade_pay_response.getString("result_code"))){
		    	tycoinAccountRechargeCallbackProcessService.tycoinAccountRechargeCallBackSaveOrUpdate(tycoinAccountRecharge, request, response);
 		    }
		} catch (Exception e) {
		}

		return result;

	}
	
	
	 /**@RequestMapping(value = "/findScannNullPayByTran",produces="application/json;charset=UTF-8",method=RequestMethod.GET)
	@ResponseBody
	public String findScannNullPayByTran(HttpServletRequest request, HttpServletResponse response) {
 		String result = "";
 		String paymentTime="2017-07-10 10:58:37";
  		
 		List <TycoinAccountRecharge> TycoinAccountRechargeList=tycoinAccountRechargeService.queryPaymentTime(paymentTime);
	    	String paymentIds="";
  	    for (TycoinAccountRecharge tycoinAccountRecharge : TycoinAccountRechargeList) {
 			ALIPayScan aLIPayScann = new ALIPayScan();
			result = aLIPayScann.test_trade_query(tycoinAccountRecharge.getPaymentId(),"");
 	    	JSONObject json= JSONObject.fromObject(result);
 	    	String code= String.valueOf(json.get("code"));
 	    	String resultMessage = "";
 	    	boolean bool=true;
			  if ("TRADE_SUCCESS".equals(code)) {
				resultMessage = "交易支付成功";
 			    String shopNotifUrl=tycoinAccountRecharge.getShopNotifUrl();
 	  			  if(StringUtil.isNotNull(shopNotifUrl)){
					  System.out.println("开始商户异步回调shopNotifUrl="+shopNotifUrl+"&resultMessage="+resultMessage+"&code=TRADE_SUCCESS&TradeNo="+tycoinAccountRecharge.getShopTradeNo()+"&paymentId="+tycoinAccountRecharge.getPaymentId());
					 HttpClientUtils  hct=new HttpClientUtils();
					hct.get(shopNotifUrl+"&resultMessage="+resultMessage+"&code=TRADE_SUCCESS&TradeNo="+tycoinAccountRecharge.getShopTradeNo()+"&paymentId="+tycoinAccountRecharge.getPaymentId());
 					tycoinAccountRecharge.setPaymentStatus(1);
					tycoinAccountRecharge.setReturnText(result);
					tycoinAccountRechargeService.save(tycoinAccountRecharge);
					paymentIds+=tycoinAccountRecharge.getPaymentId()+",";
 	  			  }
			  } 
 		}
 
 	    return paymentIds;
   

	} **/
	
	
	
	
	@RequestMapping(value = "/findScannPayByTran",produces="application/json;charset=UTF-8",method=RequestMethod.GET)
	@ResponseBody
	public String findScannPayByTran(HttpServletRequest request, HttpServletResponse response) {
 		String result = "";
		String transactionID = request.getParameter("transactionID");
		String tradeNo=request.getParameter("tradeNo");
 		String AddIp=request.getParameter("AddIp");
	 
		try {
			ALIPayScan aLIPayScann = new ALIPayScan();
			result = aLIPayScann.test_trade_query(transactionID,tradeNo);
 		} catch (Exception e) {
		}

		return result;

	}

	/**
	 * return 返回二维码的链接，二维码图片流
	 * **/
	
	@RequestMapping(value = "/tradePrecreate",produces="application/json;charset=UTF-8",method=RequestMethod.GET)
	@ResponseBody
	public String testTradePrecreate(HttpServletRequest request, HttpServletResponse response) {
 String result="";
 String aLiPaymentSwitch = LoadProperties.loadPropertiesValue("aLiPaymentSwitch");
	System.out.println(aLiPaymentSwitch);
	if ("1".equals(aLiPaymentSwitch)) {
        Map<String,String> putMap=new HashMap<String,String>();
        long dateTime=System.currentTimeMillis();
		  String outTradeNo = "ALTran" + dateTime
          + (long) (Math.random() * 1000000000L);
		  
       putMap.put("Charge", request.getParameter("Charge"));
     putMap.put("GoodsName", request.getParameter("GoodsName"));
      putMap.put("UserId", request.getParameter("UserId"));
 
     putMap.put("AddIp", IpRequestUtils.getRemoteHost(request));
    	result=isNotparam(putMap);
	     if(StringUtils.isNotBlank(result)){
	    	 return result;
	     }

	    
      AliWxPayInfo payInfo=new AliWxPayInfo();
      
 	payInfo.setCharge(Double.valueOf(putMap.get("Charge")));
	payInfo.setGoodsName(putMap.get("GoodsName"));
 	payInfo.setUserId(Integer.valueOf(putMap.get("UserId")));
	payInfo.setAddIp(putMap.get("AddIp"));
	String isMycharge=request.getParameter("isMycharge");
	TycoinAccountRecharge tycoinAccountRecharge=new TycoinAccountRecharge();
	  SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
		 String nowDate = format.format(dateTime);  
		 
	    tycoinAccountRecharge.setDateTime(dateTime);
	   tycoinAccountRecharge.setPaymentTime(nowDate);
	  tycoinAccountRecharge.setPaymentId(outTradeNo);
  
      String Logno=request.getParameter("Logno");
      
      if(!StringUtil.isNull(Logno)){
			tycoinAccountRecharge.setLogno(Logno);
		}else{
			Logno=RandomUtils.getRandomString(16);
			tycoinAccountRecharge.setLogno(Logno);
		}
      
       TycoinAccountRecharge tycoin = tycoinAccountRechargeService.findOneBylogno(Logno);
      if(tycoin!=null  && !StringUtil.isNull(String.valueOf(tycoin.getId()))){
    	  result="{\"result_code\":\"2001\",\"return_msg\":\" 订单号不能重复提交\"}";
    	  return result;
      } 
	    	 
				//商家异步回调地址，可为空
			  String aliPayNotifUrl=request.getParameter("aliPayNotifUrl");
				if(!StringUtil.isNull(aliPayNotifUrl)){
					try {
						tycoinAccountRecharge.setShopNotifUrl(URLDecoder.decode(aliPayNotifUrl,"UTF-8") );
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
			    }	
 		tycoinAccountRecharge.setPaymentId(outTradeNo);
		 tycoinAccountRecharge.setFee("0");
		 tycoinAccountRecharge.setIsOnline("0");
		 tycoinAccountRecharge.setMoney(String.valueOf((int)payInfo.getCharge()));
			tycoinAccountRecharge.setMoneyfloat((float)payInfo.getCharge()/100);
	
	    tycoinAccountRecharge.setType(String.valueOf(payInfo.getPayType()));
	   tycoinAccountRecharge.setUserId(String.valueOf(payInfo.getUserId()));
	   tycoinAccountRecharge.setAddip(payInfo.getAddIp());
		 tycoinAccountRecharge.setPayMode(2);
		 if("1".equals(isMycharge)){
			 tycoinAccountRecharge.setIsMycharge(1);
		 }else{
			 tycoinAccountRecharge.setIsMycharge(0);
		 }
	  tycoinAccountRecharge.setPaymentStatus(0);
		tycoinAccountRechargeService.save(tycoinAccountRecharge);
		try {
			ALIPayScan aLIPayScann = new ALIPayScan();
					 result = aLIPayScann.testTradePrecreate(outTradeNo,payInfo.getGoodsName(), String.valueOf(payInfo.getCharge()/100),Integer.valueOf(tycoinAccountRecharge.getMoney()), "0","一共"+String.valueOf(payInfo.getCharge())+"元" );
					 tycoinAccountRecharge.setReturnText(result);
		} catch (Exception e) {
		       e.printStackTrace();
		}
 
	}else{
		result = "{code:\"NOTICE\",resultMessage:\"对不起，支付宝支付通道已关闭\"}";
	}
		return result;

	}
	
	
	
	
	@RequestMapping(value = "/findPrecreatePayByTran",produces="application/json;charset=UTF-8",method=RequestMethod.GET)
	@ResponseBody
	public String findPrecreatePayByTran(HttpServletRequest request, HttpServletResponse response) {
 		String result = "";
		String transactionID = request.getParameter("outTradeNo");
		String tradeNo=request.getParameter("tradeNo");
		
		if(StringUtils.isBlank(transactionID)){
            result="{\"result_code\":\"2001\",\"return_msg\":\" transactionID参数不能为空\"}";
            return result;
		}
		String AddIp=request.getParameter("AddIp");
 		try {
			ALIPayScan aLIPayScann = new ALIPayScan();
			result = aLIPayScann.test_trade_query(transactionID,tradeNo);
  			
			//{\"result_code\":\"10000\",\"return_msg\":\"OK\",transaction_id:\""+outTradeNo+"\"}
			//"trade_status":"TRADE_SUCCESS"
		    JSONObject alipay_trade_pay_response = JSONObject.fromObject(result);
		    if("10000".equals(alipay_trade_pay_response.getString("result_code"))){
		    	 if("TRADE_SUCCESS".equals(alipay_trade_pay_response.getString("trade_status"))){
				    	TycoinAccountRecharge tycoinAccountRecharge=new TycoinAccountRecharge();
				    	tycoinAccountRecharge=tycoinAccountRechargeService.findOneBypaymentId(transactionID);
			         	if(tycoinAccountRecharge!=null&&tycoinAccountRecharge.getPaymentStatus()!=1){
						tycoinAccountRecharge.setReturnText(result);
		  		    	tycoinAccountRecharge.setPaymentStatus(1);
			 			tycoinAccountRechargeService.save(tycoinAccountRecharge);
			         	}
		    	 }

		    }
 		} catch (Exception e) {
		}

		return result;

	}
	
	
	@RequestMapping(value = "/notiyReturn",method=RequestMethod.POST)
 	public String notiy_return(HttpServletRequest request,HttpServletResponse response) {
		String result="";
 		 System.out.println("------------我已经进入了支付宝异步回调----------");
 		Map<String,String> params = new HashMap<String,String>();
 		Map requestParams = request.getParameterMap();
 		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
 		     String paramName = (String) iter.next();
 		     String paramValue = ((String[]) requestParams.get(paramName))[0];
 		 //    System.out.println("收到参数："+paramName + " = "+ paramValue );
 		     /*若你在notify_url后添加了自定义参数如http://www.alipay.com?a=a,请不要加入params*/
 		     params.put(paramName, paramValue);
 		}
 		String out_trade_no=params.get("out_trade_no");
 		System.out.println("out_trade_no:"+out_trade_no);
 		String trade_no=params.get("trade_no");
 		String trade_status=params.get("trade_status");
 		ALIPayScan aLIPayScann = new ALIPayScan();
 		JSONObject object = JSONObject.fromObject(aLIPayScann.test_trade_query(out_trade_no,""));
 		trade_status=object.get("code").toString();
 		System.out.println("trade_status:"+trade_status);
 		JSONObject jsonText=JSONObject.fromObject(params);
			TycoinAccountRecharge tycoinAccountRecharge=tycoinAccountRechargeService.findOneBypaymentId(out_trade_no);
			String resultMessage="";
			if("WAIT_BUYER_PAY".equals(trade_status)){
				resultMessage="交易创建，等待买家付款";
			}else if("TRADE_CLOSED".equals(trade_status)){
				resultMessage="未付款交易超时关闭，或支付完成后全额退款";
			}else if("TRADE_SUCCESS".equals(trade_status)){
				resultMessage="交易支付成功";
			}else if("TRADE_FINISHED".equals(trade_status)){
				resultMessage="交易结束，不可退款";
			}
			
			
			
    if("TRADE_SUCCESS".equals(trade_status)){
 			if(tycoinAccountRecharge!=null&&tycoinAccountRecharge.getPaymentStatus()!=1){
 				tycoinAccountRecharge.setShopTradeNo(trade_no);
 				tycoinAccountRecharge.setReturnText(jsonText.toString());
 			tycoinAccountRecharge.setPaymentStatus(1);
 			tycoinAccountRechargeService.save(tycoinAccountRecharge);
            String shopNotifUrl=tycoinAccountRecharge.getShopNotifUrl();
  			 if(StringUtil.isNotNull(shopNotifUrl)){
				  System.out.println("开始商户异步回调shopNotifUrl="+shopNotifUrl+"&resultMessage="+resultMessage+"&code="+trade_status+"&TradeNo="+tycoinAccountRecharge.getShopTradeNo()+"&paymentId="+tycoinAccountRecharge.getPaymentId());
				 HttpClientUtils  hct=new HttpClientUtils();
				hct.get(shopNotifUrl+"&resultMessage="+resultMessage+"&code="+trade_status+"&TradeNo="+tycoinAccountRecharge.getShopTradeNo()+"&paymentId="+tycoinAccountRecharge.getPaymentId());
			  }
 			  TycoinUser tycoinUser=tycoinUserService.findById(Long.valueOf(tycoinAccountRecharge.getUserId()));
 			  
 			  if(tycoinUser!=null&&StringUtil.isNotNull(String.valueOf(tycoinUser.getId()))){
 		  			tycoinAccountRechargeCallbackProcessService.rechargeCallbackProcess(tycoinAccountRecharge);
 			  }
  			result="success";
  			 
 			}
 		} else{
 			if(tycoinAccountRecharge!=null){
 				String shopNotifUrl = tycoinAccountRecharge.getShopNotifUrl();
 
				if (StringUtil.isNotNull(shopNotifUrl)) {
						HttpClientUtils hct = new HttpClientUtils();
						hct.get( shopNotifUrl + "&resultMessage="+resultMessage+"&code="+trade_status+"&TradeNo=" +tycoinAccountRecharge.getShopTradeNo()+"&paymentId="+tycoinAccountRecharge.getPaymentId());
				}
				}	
 		}
		
 		return result;
		 
 	}

	
 
	
  
 
}
